<template>
    <div
        class="accountLimit"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <cardComponent pageTitle="查询服务类-->联名卡限额查询/维护">
            <template slot="cardBody">
                <el-form
                    class="searchForm"
                    ref="searchForm"
                    :model="searchForm"
                    :rules="rules"
                    :inline="true"
                    label-position="right"
                    size="small"
                    label-width="140px"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="主卡卡号:" label-position="left" prop="mainCardNo">
                                <el-input v-model="cardInfo_3004.CARDNO" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="是否开通自动充值:"
                                label-position="left"
                                prop="isAutoRecharge"
                            >
                                <el-radio-group
                                    v-model="searchForm.isAutoRecharge"
                                    @change="handleResetLimits"
                                >
                                    <el-radio :label="'1'">是</el-radio>
                                    <el-radio :label="'0'">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="searchForm.isAutoRecharge === '1'">
                        <el-col :span="12">
                            <el-form-item label="合约限额:" label-position="left" prop="contractLimit">
                                <el-select
                                    placeholder="请选择合约限额"
                                    v-model="searchForm.contractLimit"
                                    clearable
                                >
                                    <el-option
                                        v-for="(item, index) in contractLimitList"
                                        :key="index"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="btnBox">
                        <el-button
                            type="primary"
                            size="small"
                            :loading="pageLoading"
                            @click="handleConfirm"
                            icon="el-icon-circle-check"
                        >确定</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-refresh-right"
                            @click="handleReset"
                        >重 置</el-button>
                    </el-row>
                </el-form>
            </template>
        </cardComponent>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import { cardProductCheck } from '@/utils/menuRules';
import { getDictValue, sendMessage } from '@/utils/Common';
import { getToken, getTokenHsbankNo } from '@/utils/auth';
export default {
    name: 'accountLimit',
    components: {
        cardComponent,
    },
    data() {
        return {
            pageLoading: false, // 确定按钮loading
            initData: '',
            contractLimitList: [ // 合约限额选择列表
                {
                    label: '0',
                    value: 0,
                },
                {
                    label: '1000',
                    value: 1000,
                },
                {
                    label: '2000',
                    value: 2000,
                },
                {
                    label: '3000',
                    value: 3000,
                },
            ],
            searchForm: { // 表单数据
                isAutoRecharge: undefined, // 是否开通自动充值
                contractLimit: 0, // 合约限额
            },
            rules: { // 表单校验规则
                isAutoRecharge: [{ required: true, message: '请选择是否开通自动充值', trigger: 'blur' }],
            },
        };
    },

    mounted() {
        this.init();
    },

    // 取缓存信息
    computed: mapState({
        customerInfo_3002: state => state.common.customerInfo_3002, // 客户信息
        cardInfo_3004: state => state.common.cardInfo_3004, // 默认卡信息
        cardList_3601: state => state.common.cardList_3601, // 卡列表信息
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        inlineParams: state => state.common.inlineParams, // 接口默认参数  --行内交易
        pinFlag: state => state.common.pinFlag, // 是否密码检查标志
    }),

    methods: {

        // 初始化
        async init() {
            // 查询数据库字典 获取 卡产品名称
            const productName = await getDictValue(this.cardList_3601, this.cardInfo_3004.CARDNO, 'PRODUCT', this);

            // 菜单校验
            cardProductCheck(productName, this.cardInfo_3004, this);

            // 查询初始值
            this.getInitData();
        },

        // 获取初设置查询结果
        getInitData() {
            const params = {
                cardno: this.cardInfo_3004.CARDNO,
            };

            this.$post.common.getCashInstallment(params).then((res) => {
                console.log(res, '初始化查询结果');
                if (res.status === 200) {
                    if (res.data.content.length) {
                        const data = res.data.content[res.data.content.length - 1];
                        this.initData = data;
                        const searchForm = {
                            isAutoRecharge: data.stat, // 是否开通自动充值
                            contractLimit: data.limits, // 合约限额
                        };
                        this.searchForm = JSON.parse(JSON.stringify(searchForm));
                    }
                }
            });
        },

        // 更新 联名卡限额修改 记录
        updateCashInstallment() {
            const params = {
                banknum: getTokenHsbankNo('HsbankNo'), // 银行号
                cardno: this.cardInfo_3004.CARDNO, // 卡号
                limits: this.searchForm.contractLimit, // 限额
                stat: this.searchForm.isAutoRecharge, //
                retcode: '000000',
            };

            this.$post.common.updateCashInstallment(params).then((res) => {
                if (res.status === 200) {

                }
            });
        },

        // 确定按钮点击处理事件
        handleConfirm() {
            this.pageLoading = true;

            // 跑 H003 交易
            this.$refs.searchForm.validate((valid) => {
                if (valid) {
                    if (this.initData.limits === this.searchForm.contractLimit && this.initData.stat === this.searchForm.isAutoRecharge) {
                        this.$confirm('合约未发生变化,无需变更', '提示', { customClass: 'warning', type: 'warning' }).then(() => {
                            this.pageLoading = false;
                        });
                    } else {
                        this.$confirm('您确认修改？', '温馨提示', {
                            customClass: 'warning', type: 'warning',
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                        }).then(() => {
                            // 设置请求参数 -- H003 交易
                            const appBody = {
                                cardAsn: this.cardInfo_3004.CARDNO, // 卡号
                                contractType: this.searchForm.isAutoRecharge, // 合约类型
                                contractAmount: this.searchForm.contractLimit, // 合约限额
                                depositAmount: this.searchForm.contractLimit, // 充值金额
                            };
                            const params = JSON.parse(JSON.stringify(this.inlineParams));
                            // console.log(this.defaultParams, 'this.defaultParams')
                            params.body.appHead.tranCode = 'H003';
                            params.body.appBody = appBody;

                            // 跑 H003 交易
                            this.$post.inlineTransModule.transH003(params).then((res) => {
                                this.pageLoading = false;
                                if (res.status === 200) { // 接口请求成功
                                    const result = JSON.parse(res.data.jsonRes);
                                    // console.log(params, '请求报文--H003')
                                    console.log(result, 'result--H003');
                                    if (result.sysHead.rspCd === '000000') {
                                        this.$alert(result.sysHead.rspMsg, '提示', {
                                            customClass: 'success', type: 'success',
                                        });

                                        // 跟新合约变更记录
                                        this.updateCashInstallment();

                                        // 发送短信
                                        this.handleSendMsg();
                                    } else {
                                        const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                                        this.$alert(errorMsg, result.sysHead.rspDesc, '提示', {
                                            customClass: 'error', type: 'error',
                                        });
                                    }
                                } else {
                                    this.$message.error('请求失败');
                                }
                            });
                        }).catch(() => {
                            this.pageLoading = false;
                        });
                    }
                } else {
                    this.pageLoading = false;
                }
            });
        },

        // 当限额开关选择否时 重置限额
        handleResetLimits(val) {
            if (val === '0') {
                this.searchForm.contractLimit = 0;
            }
        },

        // 维护成功 发送短信
        handleSendMsg() {
            let messageContent = '';
            if (this.searchForm.isAutoRecharge === '0') { // 关闭成功
                messageContent = '尊敬的客户,您信用卡账户自动充值加油卡功能关闭成功。该功能可通过我行信用卡APP,信用卡微信及客服中心进行开通或关闭。如有疑问，请详询95379';
            } else { // 开通成功
                messageContent = '尊敬的客户，您加油信用卡自动充值功能开通成功。该功能可通过我行信用卡APP,信用卡微信及客服中心进行开通或关闭。如有疑问，请详询95379';
            }

            // 发送短信
            sendMessage(messageContent, this);
        },

        // 充值按钮点击事件处理
        handleReset() {
            this.$refs.searchForm.resetFields();
        },
    },
};
</script>
<style lang="scss">
.accountLimit {
    .searchForm {
        .el-select {
            width: 100%;
            /* max-width: 200px; */
        }
    }
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
.accountLimit {
    min-height: 100%;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;

    .btnBox {
        margin: 30px;
        text-align: right;
    }
}
</style>
